import re
import wxextAPI
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

# 初始化
bot = wxextAPI.WXbot()
print("读取自动回复关键字")
f1 = open('res/Q.json', encoding='utf-8')
f2 = open('res/A.json', encoding='utf-8')
# f3 = open('res/fdgroups.json', encoding='utf-8')
Qconf = json.load(f1)
Aconf = json.load(f2)
# groupconf = json.load(f3)
f1.close()
f2.close()
# f3.close()
# 初始化完成
# 重要参数
GroupID = "21979780073@chatroom"
# 重要参数结束


class Request(BaseHTTPRequestHandler):
    def do_POST(self):
        datas = self.rfile.read(int(self.headers['content-length']))

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Content-length', int(self.headers['content-length']))
        self.send_header('wxext', 'post success')
        self.end_headers()

        # self.wfile.write(datas)
        HavePost(json.loads(bytes.decode(datas)))


# 当收到POST后根据类型进行处理
def HavePost(datas):
    print(datas)
    # 文本消息
    if datas["type"] == 1:
        return Msg(datas["data"])
    # 图片消息
    elif datas["type"] == 3:
        print("图片")
    # 语音消息
    elif datas["type"] == 34:
        pass
    # 好友确认消息
    elif datas["type"] == 37:
        return AgreeAddUser(datas["data"]["msg"])
    # 视频消息
    elif datas["type"] == 43:
        pass
    # 动画表情
    elif datas["type"] == 47:
        pass
    # 位置消息
    elif datas["type"] == 48:
        pass
    # 分享链接
    elif datas["type"] == 49:
        pass
    # 群成员信息更新
    elif datas["type"] == 701:
        pass
    # 群成员增加
    elif datas["type"] == 702:
        pass
    # 群成员减少
    elif datas["type"] == 703:
        pass
    # 联系人信息更新
    elif datas["type"] == 704:
        pass
    # 收款结果
    elif datas["type"] == 705:
        pass
    # 好友验证结果
    elif datas["type"] == 706:
        print(datas)
    # 创建群聊结果
    elif datas["type"] == 707:
        pass
    # xml图片地址
    elif datas["type"] == 708:
        pass
    # 登录信息-授权
    elif datas["type"] == 720:
        pass
    # 登录信息-连接
    elif datas["type"] == 721:
        pass
    # 登录信息-登录二维码变化
    elif datas["type"] == 723:
        pass
    # 登录信息-微信登录
    elif datas["type"] == 724:
        pass
    # 登录信息-微信退出
    elif datas["type"] == 725:
        pass
    # 发起语音通过
    elif datas["type"] == 726:
        pass
    # 拒绝语音通话
    elif datas["type"] == 727:
        pass
    # 接受语音通话
    elif datas["type"] == 728:
        pass
    # 插件连接断开
    elif datas["type"] == 802:
        pass
    # 微信连接断开
    elif datas["type"] == 803:
        pass
    # 系统提示点击确定
    elif datas["type"] == 810:
        pass
    # 系统消息
    elif datas["type"] == 10000:
        pass
    else:
        print("暂未支持，请联系小火车更新")


def Msg(data):
    # print(data)
    # 是否是群聊
    if "memid" in data:
        # if "在群聊中@了你" in data["des"]:
        msg = GetReply(data["msg"])
        if msg:
            bot.SendText(wxid=data["fromid"], msg=msg, atid=data["memid"])
    # 私聊
    else:
        # 判断是否是命令
        cmdres = Command(data)
        if not cmdres:
            msg = GetReply(data["msg"])
            if msg:
                bot.SendText(wxid=data["fromid"], msg=msg)


def GetReply(msg):
    for key, value in Qconf.items():
        kw = value
        res = re.findall(kw, msg)
        if len(res):
            return Aconf[key]
    return False


def Command(data):
    if "加群" in data["msg"]:
        bot.SendGroupInvite(GroupID, data["fromid"])
    return False


def AgreeAddUser(msg):
    restr = 'fromusername="(.*?)".*encryptusername="(.*?)".* ticket="(.*?)"'
    res = re.findall(restr, msg)
    if res:
        print(res)
        bot.AgreeUser(res[0][1], res[0][2])
        bot.SendText(wxid=res[0][0], msg="欢迎添加%s，加群请回复加群" % bot.nickname)
    else:
        print("获取信息失败", msg)


if __name__ == '__main__':
    host = ('localhost', 8888)
    server = HTTPServer(host, Request)
    print('简易WebServer启动, 监听POST于 %s:%s' % host)
    server.serve_forever()
